package cn.tedu.blackhorse.service.impl;

import cn.tedu.blackhorse.ex.ServiceCode;
import cn.tedu.blackhorse.ex.ServiceException;
import cn.tedu.blackhorse.mapper.UserMapper;
import cn.tedu.blackhorse.pojo.dto.UserAddNewDTO;
import cn.tedu.blackhorse.pojo.entity.User;
import cn.tedu.blackhorse.pojo.vo.UserListItemVO;
import cn.tedu.blackhorse.pojo.vo.UserStandardVO;
import cn.tedu.blackhorse.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void studentLogin(User user) {
        UserStandardVO userStandardVO = userMapper.getByUsername(user.getUsername());
        if (userStandardVO == null){
            String message = "登陆失败,用户不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        String passwordByLoginInfo = user.getPassword();
        if (!userStandardVO.getPassword().equals(passwordByLoginInfo)){
            String message = "登陆失败,密码错误";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        return;
    }

    @Override
    public void addNew(UserAddNewDTO addNewDTO) {
        UserStandardVO byUsername = userMapper.getByUsername(addNewDTO.getUsername());
        if (byUsername != null){
            String message = "新增用户失败,用户名已存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        User user = new User();
        BeanUtils.copyProperties(addNewDTO,user);
        int row = userMapper.insert(user);
        if (row != 1){
            String message = "新增用户失败,系统繁忙,请稍后重试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        UserStandardVO byId = userMapper.getById(id);
        if (byId == null){
            String message = "删除失败,所删除数据不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        int row = userMapper.deleteById(id);
        if (row != 1){
            String message = "系统繁忙,请稍后重试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
    }

    @Override
    public List<UserListItemVO> list() {
        return userMapper.list();
    }
}
